using Newtonsoft.Json;

namespace XjjXmm.Infrastructure.ToolKit
{
	/// <summary>
	/// Json操作
	/// </summary>
	public static class JsonKit
	{
		/// <summary>
		/// 将Json字符串转换为对象
		/// </summary>
		/// <param name="json">Json字符串</param>
		public static T? ToObject<T>(string? json)
		{
			if (string.IsNullOrWhiteSpace(json))
				return default;
			return JsonConvert.DeserializeObject<T>(json);
		}

        /// <summary>
        /// 将Json字符串转换为对象
        /// </summary>
        /// <param name="json">Json字符串</param>
        public static T? ToObjectFromFile<T>(string path)
        {
			var file =  File.ReadAllText(path);
			return ToObject<T>(file);
        }

        /// <summary>
        /// 将对象转换为Json字符串
        /// </summary>
        /// <param name="target">目标对象</param>
        /// <param name="isConvertToSingleQuotes">是否将双引号转成单引号</param>
        public static string ToJson(object? target, bool isConvertToSingleQuotes = false)
		{
			if (target == null)
				return string.Empty;
			var result = JsonConvert.SerializeObject(target);
			if (isConvertToSingleQuotes)
				result = result.Replace("\"", "'");
			return result;
		}

		
	}

	public static class JsonKitExtension
	{
		public static string ToJson(this object target, bool isConvertToSingleQuotes = false)
		{
			return JsonKit.ToJson(target, isConvertToSingleQuotes);
		}

		public static T? ToObject<T>(this string? target)
		{
			
			return JsonKit.ToObject<T>(target);
		}
	}
}
